<?php


namespace WenRuns\Laravel\Admin\Form\Field\MultiList;


use Encore\Admin\Facades\Admin;

class RemoveEvent
{
    /**
     * @param TableList $tableList
     */
    public static function remove(TableList $tableList)
    {
        $eventClosure = empty($tableList->buttonEventClosure) ? 0 : $tableList->buttonEventClosure;
        $emptyBody = str_replace('/', '\/', $tableList->compressHtml($tableList->multiList->emptyBody()));
        $btnClass = 'table-list-btn-remove-' . $tableList->getUniqueKey();
        $tableKey = $tableList->getTableKey();
        $script = <<<SCRIPT
$(function(){
    $(document).on("click", "#{$tableKey} .{$btnClass}", function(e){
        function remove(ele){
            if(ele.nextElementSibling && ele.nextElementSibling.dataset && ele.nextElementSibling.dataset.sub == 'true'){
                remove(ele.nextElementSibling);
            }
            ele.remove();
        }
        let doRemove = function(){
            var parent = e.currentTarget.parentElement.parentElement.parentElement;
            remove(e.currentTarget.parentElement.parentElement);
            if(parent && Array.from(parent.children).length == 0){
                parent.innerHTML = `{$emptyBody}`;
                parent.setAttribute("data-empty","true");
            }
        }
        var fn = {$eventClosure};
        if(fn){
            fn.call(this, e, doRemove);
        }else{
            doRemove();
        }
    });
});
SCRIPT;
        Admin::script($script);
    }
}
